import { API } from "@/api/modules/dwh/typings";
import { EnumProps } from "@/components/ProTable/interface";
import { ref, toValue, watchEffect } from "vue";
import { ColumnOptionsType, ColumnTypeEnum, DateRange } from "@/utils/dict";
import { simpleUserTableDataController } from "@/api/modules/dwh";
import { getColumnOptionsType } from "@/utils/TableColumnUtil";

export type LinkTable = { tableInfoId: number; valueCode: string; valueLabel: string };

export const useDimensionOptions = (tableColumn: API.TableColumnVo | string) => {
  const columnOptions = ref<EnumProps[]>([]);

  function linkTableOptions(table: LinkTable) {
    if (!table.tableInfoId || !table.valueCode || !table.valueLabel) return [];
    simpleUserTableDataController
      .pageUserTableDataUsingPOST({
        page: { pageIndex: 1, pageSize: 100 },
        query: { tableInfoId: Number(table.tableInfoId) }
      })
      .then(res => {
        let data = res.data;
        columnOptions.value = data.map((item: API.PageUserTableDataVo) => {
          let valueCode = item.tableData?.find((tableData: API.UserTableDataVo) => tableData.columnCode == table.valueCode) ?? {};
          let valueLabel =
            item.tableData?.find((tableData: API.UserTableDataVo) => tableData.columnCode == table.valueLabel) ?? {};
          return { label: valueLabel.value, value: valueCode.value };
        });
      });

    // return result;
  }

  function customOptions(options: string) {
    return options.split(",").map(item => {
      let options = item.split(":");
      return { label: options[1], value: options[0] };
    });
  }

  // 是否有下拉选项
  const getOptions = (tableColumn: API.TableColumnVo | string) => {
    if (typeof tableColumn === "string") {
      if (getColumnOptionsType(tableColumn) == ColumnOptionsType.link_table) {
        linkTableOptions(JSON.parse(tableColumn) as LinkTable);
      } else {
        columnOptions.value = customOptions(tableColumn);
      }
      return;
    }
    tableColumn = tableColumn as API.TableColumnVo;
    if (tableColumn.columnType == ColumnTypeEnum.date) {
      columnOptions.value = DateRange;
      return;
    }
    let columnOptionsType = getColumnOptionsType(tableColumn.columnOptions);
    if (columnOptionsType == ColumnOptionsType.link_table) {
      let table = JSON.parse(tableColumn.columnOptions!);
      linkTableOptions(table);
    } else if (columnOptionsType == ColumnOptionsType.custom) {
      columnOptions.value = customOptions(tableColumn.columnOptions!);
    } else {
      columnOptions.value = [];
    }
  };

  watchEffect(() => {
    let unRefValue = toValue(tableColumn);
    if (unRefValue) {
      getOptions(unRefValue);
    } else {
      columnOptions.value = [];
    }
  });

  return { columnOptions };
};
